package tgc.edu.fhh.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.fhh.custom.AjaxResult;
import tgc.edu.fhh.custom.BaseController;
import tgc.edu.fhh.custom.TablePageable;
import tgc.edu.fhh.entity.TbClass;
import tgc.edu.fhh.service.TbClassService;
import tgc.edu.fhh.web.form.TbClassForm;

@Controller
@RequestMapping(value = "/banji")
public class TbClassController extends BaseController<TbClass, Integer, TbClassForm>{
	@Autowired
	private TbClassService tbclassService;

	@Override
	public Specification<TbClass> buildSpec(TbClassForm form) {
		@SuppressWarnings("serial")
		Specification<TbClass> spec=new Specification<TbClass>() {
			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String manager = form.getManager();
				if(StringUtils.hasText(manager)) {
					rules.add(cb.like(root.get("manager"), "%"+manager+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	//分页
	@RequestMapping(value = "/page")
	@ResponseBody
	public Object page(TablePageable tablePageable, TbClassForm form) {
		PageRequest pageRequest = tablePageable.buildPageRequest();
		Specification<TbClass> spec = buildSpec(form);
		Page<TbClass> page = tbclassService.findAll(spec, pageRequest);
		return AjaxResult.buildTableResult(page);
	}
//查询
	@RequestMapping(value = "/search")
	public void search(TbClassForm form, ModelMap modelMap) {
		modelMap.put("model", form);
	}
	//保存
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(TbClassForm form) {
		try {
			TbClass model = new TbClass();
			Integer id = form.getId();
			if (id != null) {
				model = tbclassService.findById(id);
			}
			BeanUtils.copyProperties(form, model, "id");
			tbclassService.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}
	

	
}
